package cn.edu.nju.askinginhand.activity;

import static cn.edu.nju.askinginhand.constant.QuesType.pic_class1;
import static cn.edu.nju.askinginhand.constant.QuesType.pic_class2;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import cn.edu.nju.askinginhand.util.JSONParser;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;

/**
 * 
 * @author ZhangZu
 * 
 */
public class PictureQuesActivity extends Activity {
	// takepicture panel widgets
	private Button startCaptureBtn = null;
	
	private String actionUrl = JSONParser.rootUrl+"/UploadServlet?uid="+LoginActivity.uid;
	public static String uploadFile = "";
	private String newName ;
	// problem panel widgets
	private View problemPanel;
	private EditText titleEdit = null;
	private Spinner firstSpinner = null;
	private Spinner secondSpinner = null;
	private Button publishBtn = null;
    private ImageView imageView;
	private int status = 0;// 0:ready 1:take over
	private String[] buttonTexts = { "拍摄照片", "重新拍摄" };
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.picture_ques);
		startCaptureBtn = (Button) findViewById(R.id.startCaptureBtn);
		problemPanel = (View) findViewById(R.id.problemPanel);
		titleEdit = (EditText) findViewById(R.id.titleEdit);
		firstSpinner = (Spinner) findViewById(R.id.firstSpinner);
		secondSpinner = (Spinner) findViewById(R.id.secondSpinner);
		publishBtn = (Button) findViewById(R.id.publishBtn);
		imageView = (ImageView) this.findViewById(R.id.image);
		initStartCaptureBtn();
		initPublishBtn();
		initSpinner();
		updateAllWidgets();
	}
	
  
	public void initStartCaptureBtn() {
		startCaptureBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				startActivityForResult(new Intent(PictureQuesActivity.this,PhotoTakenActivity.class), 0);
				
				status = 1;
				updateAllWidgets();
			}
		});
	}

	public void initSpinner() {
		ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this, R.layout.questype_spinner_item,
				R.id.spinnerText, pic_class1);

		firstSpinner.setAdapter(adapter1);
		firstSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int position, long id) {
				ArrayAdapter<String> adapter2 = null;
				if (position == 0) {
					secondSpinner.setVisibility(View.INVISIBLE);
				} else {
					secondSpinner.setVisibility(View.VISIBLE);
					adapter2 = new ArrayAdapter<String>(PictureQuesActivity.this,
							R.layout.questype_spinner_item, R.id.spinnerText,
							pic_class2[position]);
					secondSpinner.setAdapter(adapter2);
				}
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				secondSpinner.setVisibility(View.INVISIBLE);
			}
		});
	}
	
	public void initPublishBtn() {
		publishBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				
				String type = firstSpinner.getSelectedItem().toString();
				if(secondSpinner.getVisibility()==View.VISIBLE&&secondSpinner.getSelectedItem()!=null)
					type = type+"-"+secondSpinner.getSelectedItem().toString();

				List <NameValuePair> params = new ArrayList <NameValuePair>();
				params.add(new BasicNameValuePair("title", titleEdit.getText().toString()));
				params.add(new BasicNameValuePair("content", " "));
				params.add(new BasicNameValuePair("uid", LoginActivity.uid)); 
				params.add(new BasicNameValuePair("type",type));
				String imagePath = uploadFile();
				params.add(new BasicNameValuePair("image", imagePath)); 
				String raw = JSONParser.getOut("PictureQuestionAction"+LoginActivity.filter,params);
				//Toast.makeText(this, raw, Toast.LENGTH_SHORT).show();		
				String result= JSONParser.getStringData(raw);
				if(result==null){
					
					return;
				}
				if(result.equals("success")){
					Toast.makeText(PictureQuesActivity.this, "上传成功",
							Toast.LENGTH_LONG).show();
					
				}else{
					Toast.makeText(PictureQuesActivity.this, "上传失败",
							Toast.LENGTH_LONG).show();
					
				}
				//FileOutputStream fout=new FileOutputStream(file);	
				/**
				 * TODO: publish the problem.
				 * With the location information
				 */
				//Location location = LocationGetter.getInstance().getLocation();
			}
		});
	}

	// called when after capture
	public void updateAllWidgets() {
		startCaptureBtn.setText(buttonTexts[status]);
		//problemPanel.setVisibility(visibles[status]);
	}
	 @Override
	    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	            if (requestCode == 0 && resultCode == Activity.RESULT_OK) {
	            	/*    String date=System.currentTimeMillis()+"";
	            	    File directory=new File(Environment.getExternalStorageDirectory(),"pictures");
	            	    if(!directory.exists())
	            	        directory.mkdir();
	            	    System.out.println(directory.getPath());
	            	    File file1=new File(directory.getPath(),date+".jpg");
	            	    
	            	    try {
							if(file1.createNewFile()){
								File file2=new File(Environment.getExternalStorageDirectory(),"camera.jpg");
								FileInputStream fin=new FileInputStream(file2);
								FileOutputStream fout=new FileOutputStream(file1);
								byte[] buf=new byte[1024];
								while(true){
									   int ins=fin.read(buf);
									   if(ins==-1){
									      fin.close();
									      fout.flush();
									      fout.close();
					                      break;
									   }else
									      fout.write(buf,0,ins);
									  }
								this.imageView.setImageDrawable(Drawable.createFromPath(file1.getAbsolutePath()));
		                    // for(String s:bundle.keySet()){
		                    // Log.v("cam.demo", s);
		                    // }
		                   // this.imageView.setScaleType(ScaleType.CENTER_INSIDE);
		                    this.imageView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,500));
		                    Log.v("cam.demo", "====>" + data);
								
							}else{
								System.out.println("error");
							}
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}*/
	                    
	            	File file1=new File(uploadFile);  
	            	this.imageView.setImageDrawable(Drawable.createFromPath(file1.getAbsolutePath()));
	            	
	            	
	            	
	            	
	            	
	            }
	            	
	            	
	    }
	 
	  /* 上传文件至Server的方法 */
	    private String uploadFile()
	    {
	      newName=uploadFile;
	      String end = "\r\n";
	      String twoHyphens = "--";
	      String boundary = "*****";
	      StringBuffer filePath =new StringBuffer();
	      try
	      {
	        URL url =new URL(actionUrl);
	        HttpURLConnection con=(HttpURLConnection)url.openConnection();
	        /* 允许Input、Output，不使用Cache */
	        con.setDoInput(true);
	        con.setDoOutput(true);
	        con.setUseCaches(false);
	        /* 设置传送的method=POST */
	        con.setRequestMethod("POST");
	        /* setRequestProperty */
	        con.setRequestProperty("Connection", "Keep-Alive");
	        con.setRequestProperty("Charset", "UTF-8");
	        con.setRequestProperty("Content-Type",
	                           "multipart/form-data;boundary="+boundary);
	        /* 设置DataOutputStream */
	        DataOutputStream ds = 
	          new DataOutputStream(con.getOutputStream());
	        ds.writeBytes(twoHyphens + boundary + end);
	        ds.writeBytes("Content-Disposition: form-data; " +
	                      "name=\"file1\";filename=\"" +
	                      newName +"\"" + end);
	        ds.writeBytes(end);   

	        /* 取得文件的FileInputStream */
	        FileInputStream fStream = new FileInputStream(uploadFile);
	        /* 设置每次写入51200bytes */
	        int bufferSize = 51200;
	        byte[] buffer = new byte[bufferSize];

	        int length = -1;
	        /* 从文件读取数据至缓冲区 */
	        while((length = fStream.read(buffer)) != -1)
	        {
	          /* 将资料写入DataOutputStream中 */
	          ds.write(buffer, 0, length);
	        }
	        ds.writeBytes(end);
	        ds.writeBytes(twoHyphens + boundary + twoHyphens + end);

	        /* close streams */
	        fStream.close();
	        ds.flush();

	        /* 取得Response内容 */
	        InputStream is = con.getInputStream();
	        int ch;
	        
	        while( ( ch = is.read() ) != -1 )
	        {
	        	filePath.append( (char)ch );
	        }
	        Toast.makeText(PictureQuesActivity.this, "上传成功"+filePath.toString().trim(),
					Toast.LENGTH_LONG).show();
	        /* 将Response显示于Dialog */
	     
	        /* 关闭DataOutputStream */
	        ds.close();
	      }
	      catch(Exception e)
	      {
	    	  Toast.makeText(PictureQuesActivity.this, "失败",
	  				Toast.LENGTH_LONG).show();
	      }
	      return filePath.toString();
	    }

}
